//
//  FTPhotoAlbumController.m
//  Decathlon
//
//  Created on 14-2-10.(相册展示视图)
//  Copyright (c) 2014年. All rights reserved.
//

#import "FTPhotoAlbumController.h"
#import "FTAlbumPhotosController.h"
#import "FTAlbumPhotoControllerDelegate.h"
#import "RCSAlbumPhotosCell.h"

static const CGFloat kGroupCellHeight  = 80.0f;
#define HEADHEIGHT   30.f

@interface FTPhotoAlbumController ()

@end

@implementation FTPhotoAlbumController
@synthesize groupArray = _groupArray;
@synthesize albumType = _albumType;
@synthesize photoCanEdit = _photoCanEdit;

static ALAssetsLibrary     *_assetsLibrary = NULL;

- (void)dealloc
{
    self.albumDelegate = nil;
    self.videoDelegate = nil;
    self.groupArray = nil;
    self.groupTableView = nil;
}

- (void)populatePhotoGalleries
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _assetsLibrary = [[ALAssetsLibrary alloc] init];
    });
    
    _groupArray = [[NSMutableArray alloc] init];
    
    @autoreleasepool
    {
        __weak typeof(self) weakSelf = self;
        //ALAssetsGroupAll,添加这个“照片图库”相册显示不出来
        //vLOG(@"asset:%@",_assetsLibrary);
        [_assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupLibrary | ALAssetsGroupAlbum | ALAssetsGroupSavedPhotos   usingBlock:^(ALAssetsGroup *group, BOOL *stop)
         {
             //PP_LOG(@"相册Block回调%@",_assetsLibrary);
             
             if (group == nil)
             {
                 if (weakSelf.groupTableView)
                 {
                     dispatch_async(dispatch_get_main_queue(), ^{
                         
                         [weakSelf.groupTableView reloadData];
                         
                         if (weakSelf.groupArray.count <= 0) {
                             [weakSelf showTipView];
                         }
                     });
                 }
             }
             else
             {
                 //[group setAssetsFilter:[ALAssetsFilter allPhotos]];//过滤视频
                 [group setAssetsFilter:[ALAssetsFilter allAssets]];
                 
                 NSInteger count = [group numberOfAssets];//调用这个方法崩溃
                 if (count == 0)
                 {
                     return;
                 }
               
                 if (weakSelf.groupArray)
                 {
                     if ([[group valueForProperty:ALAssetsGroupPropertyType] unsignedIntegerValue] == ALAssetsGroupSavedPhotos)
                     {
                         [weakSelf.groupArray insertObject:group atIndex:0];
                     }
                     else
                     {
                         [weakSelf.groupArray addObject:group];
                     }
                 }
             }
         }
         failureBlock:^(NSError *error)
         {
             [weakSelf showNoAuthorizationView];
             
         }];
    }
}

/**
 *初始化initGroupTableView
 */
-(void)initGroupTableView
{
    CGRect kFrame = [UIScreen mainScreen].applicationFrame;
    
    _groupTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,
                                                                    0,
                                                                    kFrame.size.width,
                                                                    kFrame.size.height + (SYSTEM_VERSION >= 7.0 ? 20 : 0))];
    _groupTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _groupTableView.dataSource = self;
    _groupTableView.delegate = self;
    _groupTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _groupTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_groupTableView];
}

/**
 *无本地图片时提示界面
 */
-(void)showTipView
{
    [self.groupTableView removeFromSuperview];
    
    UIView *bgView = [[UIView alloc] initWithFrame:self.view.bounds];
    bgView.backgroundColor = [UIColor clearColor];
    bgView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:bgView];
    
    UIImageView *tipViewImage = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.bounds.size.width-50)/2,
                                                                              (self.view.bounds.size.height-40-20)/2-50,
                                                                              50,
                                                                              40)];
    tipViewImage.image = [UIImage imageNamed:@"icon_picture_normal"];
    [bgView addSubview:tipViewImage];
    
    UILabel *tiplab = [[UILabel alloc] initWithFrame:CGRectMake((self.view.bounds.size.width-200)/2,tipViewImage.frame.origin.y+tipViewImage.frame.size.height + 10, 200, 20)];
    tiplab.textAlignment = NSTextAlignmentCenter;
    tiplab.backgroundColor= [UIColor clearColor];
    tiplab.font = [UIFont systemFontOfSize:15];
    tiplab.textColor = RGB(134, 139, 142);
    tiplab.text = @"还没有本地图片哦";
    [bgView addSubview:tiplab];
}

- (void)showNoAuthorizationView
{
    // 没有权限，要提示给用户。
    UILabel *lblPrompt = [[UILabel alloc] init];
    if (SYSTEM_VERSION < 6.0)
    {
        [lblPrompt setText:@"请在iPhone的“设置-定位服务”选项中，允许使用定位服务功能。"];
    }
    else
    {
        [lblPrompt setText:@"请在iPhone的“设置-隐私-照片”选项中，允许访问你的手机相册。"];
    }
    lblPrompt.frame = CGRectMake(20, 100, [[UIScreen mainScreen] bounds].size.width - 40, 30);
    lblPrompt.numberOfLines = 0;
    lblPrompt.lineBreakMode = NSLineBreakByWordWrapping;
    [lblPrompt setFont:[UIFont systemFontOfSize:12.0f]];
    [lblPrompt setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:lblPrompt];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //self.strNavTitle = @"照片";
    self.view.backgroundColor = [UIColor whiteColor];
    [self setRightText:@"取消"];
    
    
    if (SYSTEM_VERSION >= 7.0)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    [self initGroupTableView];
    
    [self populatePhotoGalleries];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger groupCount = [self.groupArray count];
    return groupCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger indexRow = indexPath.row;
    
    static NSString *groupIdentifier = @"GroupIdentifier";
    RCSAlbumPhotosCell *cell = [tableView dequeueReusableCellWithIdentifier:groupIdentifier];
    if (cell == nil)
    {
        cell = [[RCSAlbumPhotosCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:groupIdentifier];
    }
    
    ALAssetsGroup *group = [self.groupArray objectAtIndex:indexRow];
    UIImage *groupImg = [UIImage imageWithCGImage:[group posterImage]];
    NSString *groupName = (NSString *)[group valueForProperty:ALAssetsGroupPropertyName];
    NSInteger groupCount = group.numberOfAssets;
    [cell setGroupImage:groupImg assetName:groupName groupAssetCount:groupCount];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.groupTableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ALAssetsGroup *group = [self.groupArray objectAtIndex:indexPath.row];
    
    FTAlbumPhotosController *photosController = [[FTAlbumPhotosController alloc] initWithALAssetsGroup:group];
    photosController.albumDelegate = self.albumDelegate;
    photosController.videoDelegate = self.videoDelegate;
    photosController.isComeFromWiFi = self.isComeFromWiFi;
    photosController.albumType = self.albumType;
    photosController.photoCanEdit = self.photoCanEdit;
    [self.navigationController pushViewController:photosController animated:YES];
}

#pragma mark - UITableViewDelegate

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, HEADHEIGHT)];
    headView.backgroundColor = [UIColor clearColor];
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kGroupCellHeight;
}

//浏览相册
- (void)browserSelectedAlbum:(id)sender
{
    UIButton *groupBtn = (UIButton *)sender;
    ALAssetsGroup *group = [self.groupArray objectAtIndex:groupBtn.tag];
    
    FTAlbumPhotosController *photosController = [[FTAlbumPhotosController alloc] initWithALAssetsGroup:group];
    photosController.albumDelegate = self.albumDelegate;
    photosController.videoDelegate = self.videoDelegate;
    photosController.isComeFromWiFi = self.isComeFromWiFi;
    photosController.albumType = self.albumType;
    photosController.photoCanEdit = self.photoCanEdit;
    [self.navigationController pushViewController:photosController animated:YES];
}

//取消
-(void)rightButtonPressed:(id)action
{
    if (AlbumType_SingleForSendingForFile == self.albumType)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
